package com.flex.core.scheduling;

import org.quartz.SchedulerException;
import org.springframework.beans.BeansException;
import org.springframework.beans.factory.DisposableBean;
import org.springframework.beans.factory.FactoryBean;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;

/**
 * spring中配置的定时任务管理类，在spring加载时获得spring的上下文，并调用SchedulerFactory进行定时任务的运行
 * 
 * @author radio
 * 
 * @see SchedulerFactory
 * 
 */
public class SchedulingFactoryBean implements FactoryBean,
		ApplicationContextAware, InitializingBean, DisposableBean {

	private SchedulerFactory sched = null;

	private ApplicationContext applicationContext;

	public Object getObject() throws Exception {
		return sched;
	}

	@SuppressWarnings("unchecked")
	public Class getObjectType() {
		if (sched == null) {
			return null;
		}
		return this.sched.getClass();
	}

	public boolean isSingleton() {
		return true;
	}

	public void afterPropertiesSet() throws Exception {
		sched = new SchedulerFactory();
		try {
			sched.start(this.applicationContext);
		} catch (SchedulerException e) {
			e.printStackTrace();
		}
	}

	public void destroy() throws Exception {
		if (sched != null) {
			sched.shutdown();
		}
	}

	public void setApplicationContext(ApplicationContext applicationContext)
			throws BeansException {
		this.applicationContext = applicationContext;
	}
}
